package com.angel.web.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.angel.core.Constants;
import com.angel.core.base.JsonEntity;
import com.angel.core.util.FileUpload;
import com.angel.core.util.JsonUtil;
import com.angel.core.util.MD5Util;
import com.angel.core.util.SMSUtils;
import com.angel.health.BuzDoctor;
import com.angel.health.SMS;
import com.angel.health.SysSendMessage;
import com.angel.provider.app.WangYiProvider;
import com.angel.provider.health.BuzDoctorProvider;
import com.angel.provider.sys.SysSendMessageProvider;

/**
 * @author 作者姓名 cheng
 * @version 创建时间：2016年9月19日 下午3:38:30 类说明 app---医师操作
 */
@Controller
@RequestMapping("app/doct")
public class AppDoctorController {

	@Autowired
	private BuzDoctorProvider provider;
	@Autowired
	private SysSendMessageProvider sysSendMessageProvider;
	@Autowired
	private WangYiProvider wyService;

	/**
	 * 获取医师信息
	 * 
	 * @param doctor
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "index", produces = "application/json; charset=utf-8")
	public String index(BuzDoctor doctor, HttpServletRequest req) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (doctor.getStatus() == null && doctor.getId() == null) {
			return JsonUtil.toJson(new JsonEntity("-1", "参数不正确！"));
		}
		doctor.setDelFlag(1);
		list = provider.findDoctorAll(doctor);

		return JsonUtil.toJson(new JsonEntity("200", list));
	}

	/**
	 * 添加医师信息 添加医师信息，同步如系统用户中
	 * 
	 * @param doctor
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "addDoctor", produces = "application/json; charset=utf-8")
	public String addDoctor(BuzDoctor doctor) {
		List<Map<String, Object>> doctorList = provider
				.findDoctorAll(new BuzDoctor(doctor.getMobile(), doctor.getEmail()));
		int status = 0;
		if (StringUtils.isEmpty(doctor.getPassword())) {
			return JsonUtil.toJson(new JsonEntity("-1", "请输入密码"));
		}
		if (doctorList.size() > 0) {
			String token = doctorList.get(0).get("token").toString();
//			status = doctorList.get(0).get("status").toString();
			doctor.setToken(token);
			String id = doctorList.get(0).get("id").toString();
			provider.delete(id);
		}
		doctor.setPassword(MD5Util.getMD5(doctor.getPassword()));
		doctor.setStatus(status);
		doctor.setDelFlag(1);
		doctor.setIsFree(1);
		// 写入医师信息
		Map<String, String> map = provider.save(doctor);
		if ("1".equals(map.get("code"))) {
			return JsonUtil.toJson(new JsonEntity("200", "成功"));
		} else {
			return JsonUtil.toJson(new JsonEntity("-1", "注册失败！"));
		}
	}

	/**
	 * 完善信息
	 * 
	 * @param doctor
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "edit", produces = "application/json; charset=utf-8")
	public String edit(@ModelAttribute("doctor") BuzDoctor doctor, HttpServletRequest request) {

		if (doctor.getId() == null) {
			return JsonUtil.toJson(new JsonEntity("-1", "参数不正确"));
		}
		try {
			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultiValueMap<String, MultipartFile> multiFileMap = req.getMultiFileMap();
			String uploadUrl;
			if (multiFileMap != null) {
				uploadUrl = FileUpload.uploadForFastdfs(multiFileMap);
				doctor.setPhoto(uploadUrl);
			}
		} catch (Exception e) {

		}
		int updateById = provider.updateById(doctor);
		if (updateById > 0) {
			try {
				doctor = provider.findById(doctor);
				String updateUinfo = wyService.updateUinfo(JsonUtil.toJson(doctor));
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
			return JsonUtil.toJson(new JsonEntity("200", provider.findById(doctor)));
		} else {
			return JsonUtil.toJson(new JsonEntity("-1", "编辑失败！"));
		}
	}

	/**
	 * 医师登录 查询用户中医师角色 若用户中存在则
	 * 
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "login", produces = "application/json; charset=utf-8")
	public String login(BuzDoctor buzDoctor) {
		buzDoctor.setPassword(MD5Util.getMD5(buzDoctor.getPassword()));
		// List<Map<String, Object>> list = sysUserProvider.findAllUser(user);
		// if (list.size() > 0) {
		// return JsonUtil.toJson(new JsonEntity("200", list.get(0)));
		// } else {
		// BuzDoctor buzDoctor = new BuzDoctor();
		// BeanUtils.copyProperties(user, buzDoctor);
		buzDoctor.setDelFlag(1);
		List<Map<String, Object>> doctorAll = provider.findDoctorAll(buzDoctor);
		if (doctorAll.size() > 0) {
			return JsonUtil.toJson(new JsonEntity("200", doctorAll.get(0)));
		}
		// }
		return JsonUtil.toJson(new JsonEntity("-1", "登录失败！"));
	}

	/**
	 * 忘记密码
	 * 
	 * @param doctor
	 *            修改医师信息成功后修改用户信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "iforgot", produces = "application/json; charset=utf-8")
	public String iforgot(BuzDoctor doctor) {
		if (StringUtils.isEmpty(doctor.getPassword())) {
			return JsonUtil.toJson(new JsonEntity("-1", "请输入正确的密码！"));
		}
		List<Map<String, Object>> list = provider.findDoctorByPhone(doctor);
		if (list.size() > 0) {
			doctor.setId(Integer.parseInt(list.get(0).get("id").toString()));
			doctor.setPassword(MD5Util.getMD5(doctor.getPassword()));
			int updateById = provider.updateById(doctor);
			if (updateById > 0) {
//				SysUser user = new SysUser();
//				BeanUtils.copyProperties(doctor, user);
//				List<Map<String, Object>> userList = sysUserProvider.findUserByPhone(user);
//				if (userList.size() > 0) {
//					user.setId(Integer.parseInt(userList.get(0).get("id").toString()));
//					sysUserProvider.updateById(user);
//				}
				return JsonUtil.toJson(new JsonEntity("200", "修改成功"));
			}
		}
		return JsonUtil.toJson(new JsonEntity("-1", "不存在的手机号码！"));
	}

	/**
	 * 
	 * @param mobile
	 * @param type
	 *            1.注册 2.找回密码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getCode", produces = "application/json; charset=utf-8")
	public String getCode(String mobile, String type) {
		if (StringUtils.isEmpty(mobile)) {
			return JsonUtil.toJson(new JsonEntity("-1", "手机号不存在！"));
		}

		String content = "为您在天使健康的找回密码验证码【天使健康】";
		List<Map<String, Object>> doctorAll = provider.findDoctorAll(new BuzDoctor(mobile, ""));
		if ("1".equals(type)) {
			content = "为您在天使健康的注册验证码【天使健康】";
			if (doctorAll.size() > 0) {
				return JsonUtil.toJson(new JsonEntity("-1", "已注册"));
			}
		} else {
			if (doctorAll.size() == 0) {
				return JsonUtil.toJson(new JsonEntity("-1", "未注册"));
			}
		}

		String code = "";
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			int nextInt = random.nextInt(10);
			code += nextInt;
		}
		content = code + content;
		SysSendMessage sysSendMessage = new SysSendMessage(1, mobile, content, null);
		int insert = sysSendMessageProvider.insert(sysSendMessage);
		if (insert > 0) {
			String single = Constants.SEND_SMS_SINGLE;
			JsonEntity json = SMSUtils.send(
					new SMS(sysSendMessage.getId().toString(), mobile, content, sysSendMessage.getId().toString(), ""),
					single);
			if ("200".equals(json.getCode())) {
				return JsonUtil.toJson(new JsonEntity("200", code));
			}
			return JsonUtil.toJson(json);
		}
		return JsonUtil.toJson(new JsonEntity("-1", "发送失败！"));
	}

	/**
	 * 根据旧密码修改密码 若医师表中修改成功 则修改用户表中医师信息
	 */
	@ResponseBody
	@RequestMapping(value = "upfop", produces = "application/json; charset=utf-8")
	public String updatePwordForOldPword(@ModelAttribute("buzDoctor") BuzDoctor buzDoctor) {
		if (StringUtils.isEmpty(buzDoctor.getOldPassword())) {
			return JsonUtil.toJson(new JsonEntity("-1", "旧密码不正确"));
		}
		BuzDoctor bd = new BuzDoctor();
		bd.setMobile(buzDoctor.getMobile());
		bd.setPassword(MD5Util.getMD5(buzDoctor.getOldPassword()));
		List<Map<String, Object>> list = provider.findDoctorAll(bd);
		if (list.size() > 0) {
			buzDoctor.setId(Integer.parseInt(list.get(0).get("id").toString()));
			buzDoctor.setPassword(MD5Util.getMD5(buzDoctor.getPassword()));
			int updateById = provider.updateById(buzDoctor);
			if (updateById > 0) {
//				SysUser user = new SysUser();
//				BeanUtils.copyProperties(buzDoctor, user);
//				List<Map<String, Object>> userList = sysUserProvider.findUserByPhone(user);
//				if (userList.size() > 0) {
//					user.setId(Integer.parseInt(userList.get(0).get("id").toString()));
//					sysUserProvider.updateById(user);
//				}
				return JsonUtil.toJson(new JsonEntity("200", "修改成功"));
			}
		}
		return JsonUtil.toJson(new JsonEntity("-1", "旧密码不正确"));
	}

	/**
	 * 上传医师执照
	 */
	@ResponseBody
	@RequestMapping(value = "upload", produces = "application/json; charset=UTF-8")
	public String upload(BuzDoctor doctor, MultipartHttpServletRequest request) {
		try {

			if (doctor.getId() == null) {
				return JsonUtil.toJson(new JsonEntity("-1", "参数不正确"));
			}
			MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
			String uploadUrl = FileUpload.uploadForFastdfs(multiFileMap);
			doctor.setPhysicianQualificationCertificate(uploadUrl);
			int i = provider.updateById(doctor);
			if (i > 0) {
				return JsonUtil.toJson(new JsonEntity("200", "上传成功"));
			} else {
				return JsonUtil.toJson(new JsonEntity("-1", "失败"));
			}
		} catch (Exception e) {
			// e.printStackTrace();
			return JsonUtil.toJson(new JsonEntity("-1", "失败"));
		}
	}
}
